<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>
        管理员列表
    </title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <script type="text/javascript" th:src="@{/lib/loading/okLoading.js}"></script>
    <link rel="stylesheet" th:href="@{/css/main.css}" media="all">
    <link rel="stylesheet" th:href="@{/css/bootstrap.css}">
    <!--导入ElementUI样式列表，css样式一般都在页面头部-->
    <link rel="stylesheet" th:href="@{/css/index.css}">
</head>
<style>
    .demo-table-expand {
        font-size: 0;
    }

    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }

    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }
</style>
<body>
<div class="x-nav">
            <span class="layui-breadcrumb">
              <a><cite>首页</cite></a>
              <a><cite>管理员管理</cite></a>
              <a><cite>管理员列表</cite></a>
            </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
       href="javascript:location.replace(location.href);" title="刷新"><i class="layui-icon"
                                                                        style="line-height:30px">ဂ</i></a>
</div>
<div class="x-body">
    <div class="app-container" id="app">
        <div class="search-div">
            <el-form label-width="70px" size="small">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="关 键 字">
                            <el-input style="width: 95%" v-model="searchMap.keyword"
                                      placeholder="用户名/姓名/手机号码"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="操作时间">
                            <el-date-picker
                                    v-model="createTimes"
                                    type="datetimerange"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    style="margin-right: 10px;width: 100%;"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row style="display:flex">
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData(1)">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetData">重置</el-button>
                    <el-button type="success" icon="el-icon-plus" size="mini" @click="add">添 加</el-button>
                </el-row>
                <el-divider></el-divider>
            </el-form>
        </div>
        <el-table
                v-loading="listLoading"
                :data="list"
                stripe
                border
                style="width: 100%;margin-top: 10px;">
            <el-table-column type="expand">
                <template slot-scope="props">
                    <el-form label-position="left" inline class="demo-table-expand">
                        <el-form-item label="所属小区">
                            <span>{{ props.row.communityName }}</span>
                        </el-form-item>
                        <el-form-item label="登录名">
                            <span>{{ props.row.loginName }}</span>
                        </el-form-item>
                        <el-form-item label="真实名称">
                            <span>{{ props.row.name }}</span>
                        </el-form-item>
                        <el-form-item label="密码">
                            <span>{{ codeMask(props.row.password) }}</span>
                        </el-form-item>
                        <el-form-item label="手机">
                            <span>{{ props.row.telephone }}</span>
                        </el-form-item>
                        <el-form-item label="邮箱">
                            <span>{{ props.row.email }}</span>
                        </el-form-item>
                        <el-form-item label="创建日期">
                            <span>{{ props.row.createTime }}</span>
                        </el-form-item>
                        <el-form-item label="分配角色">
                            <el-button
                                    type="warning"
                                    size="mini"
                                    @click="showAssignRole(props.row)">选择角色
                            </el-button>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column
                    label="用户 ID"
                    prop="id">
            </el-table-column>
            <el-table-column
                    label="登录账号"
                    prop="loginName">
            </el-table-column>
            <el-table-column
                    label="真实名称"
                    prop="name">
            </el-table-column>
            <el-table-column
                    label="手机号"
                    prop="telephone">
            </el-table-column>
            <el-table-column
                    label="邮箱"
                    prop="email">
            </el-table-column>
            <el-table-column
                    label="创建日期"
                    prop="createTime">
            </el-table-column>
            <el-table-column label="状态" width="80">
                <template slot-scope="scope">
                    <el-switch
                            v-model="scope.row.status === 1"
                            @change="switchStatus(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button
                            type="primary"
                            size="mini"
                            @click="edit(scope.row.id)">编辑
                    </el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            @click="removeDataById(scope.row.id)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog title="分配角色" :visible.sync="dialogRoleVisible">
            <el-form label-width="80px">
                <el-form-item label="用户名">
                    <el-input disabled :value="sysUser.loginName"></el-input>
                </el-form-item>

                <el-form-item label="角色列表">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
                    </el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="userRoleIds" @change="handleCheckedChange">
                        <el-checkbox v-for="role in allRoles" :key="role.roleId" :label="role.roleId">
                            {{role.roleName}}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button type="primary" @click="assignRole" size="small">保存</el-button>
                <el-button @click="dialogRoleVisible = false" size="small">取消</el-button>
            </div>
        </el-dialog>
        <el-dialog title="添加/修改" :visible.sync="dialogVisible" width="40%">
            <el-form :rules="rules" ref="dataForm" :model="sysUser" label-width="100px" size="small"
                     style="padding-right: 40px;">
                <el-form-item v-if="!sysUser.id" label="所属小区" prop="communityName">
                    <el-select v-model="sysUser.communityName" filterable placeholder="--请选择所属小区--">
                        <el-option
                                v-for="item in findByCommunityName"
                                :key="item.index"
                                :label="item.communityName"
                                :value="item.communityName"
                                @click.native="buildingFindAllByName(sysUser.communityName)">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="用户名" prop="loginName">
                    <el-input v-model="sysUser.loginName"/>
                </el-form-item>
                <el-form-item v-if="!sysUser.id" label="密码" prop="password">
                    <el-input v-model="sysUser.password" type="password"/>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="sysUser.name"/>
                </el-form-item>
                <el-form-item label="手机" prop="telephone">
                    <el-input v-model="sysUser.telephone"/>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="sysUser.email"/>
                </el-form-item>
                <el-form-item style="display:none">
                    <el-input v-model="sysUser.communityId"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        			        <el-button @click="dialogVisible = false" size="small"
                                       icon="el-icon-refresh-right">取 消</el-button>
        			        <el-button type="primary" icon="el-icon-check" @click="saveOrUpdate()"
                                       size="small">确 定</el-button>
        			      </span>
        </el-dialog>
        <br/>
        <!-- 分页组件 -->
        <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-size="searchMap.limit"
                layout="prev, pager, next,sizes"
                :page-sizes="[2,10,20]"
                style="text-align: right;"
                :total="total">
        </el-pagination>
    </div>
</div>
<script th:src="@{/lib/layui/layui.js}" charset="utf-8"></script>
<!--js脚本一般是放在页面尾部-->
<!--Vue js脚本-->
<script th:src="@{/js/vue.js}" charset="utf-8"></script>
<!--引入ElementUI组件库-->
<script th:src="@{/js/index.js}" charset="utf-8"></script>
<!--引入Axios js脚本-->
<script th:src="@{/js/axios.js}" charset="utf-8"></script>
<!--引入时间插件包Momentjs-->
<script th:src="@{/js/moment.min.js}" charset="utf-8"></script>

<script>
    var app = new Vue({
        el: "#app",//声明当前Vue在页面的作用域
        data: {
            listLoading: true,			// 数据是否正在加载
            list: null, 					// banner列表
            total: 0, 					// 数据库中的总记录数
            page: 1, 						// 默认页码
            limit: 2, 					// 每页记录数
            searchMap: {"createTimeBegin": "", "createTimeEnd": "", "keyword": this.keyword, "page": 1, "limit": 2},
            createTimes: [],
            dialogVisible: false,
            sysUser: {communityId: ''},
            dialogRoleVisible: false,
            allRoles: [], // 所有角色列表
            userRoleIds: [], // 用户的角色ID的列表
            isIndeterminate: false, // 是否是不确定的
            checkAll: false, // 是否全选
            findByCommunityName: [],
            rules: {
                communityName: [
                    {required: true, message: '请输入所属小区名称', trigger: 'blur'}
                ],
                loginName: [
                    {required: true, message: '请输入用户名', trigger: 'blur'}
                ],
                password: [
                    {required: true, message: '请输入密码', trigger: 'blur'}
                ],
                name: [
                    {required: true, message: '请输入姓名', trigger: 'blur'}
                ],
                telephone: [
                    {required: true, message: '请输入手机号', trigger: 'blur'}
                ],
                email: [
                    {required: true, message: '请输入输邮箱', trigger: 'blur'}
                ]
            }
        },
        methods: {
            //分配角色
            assignRole () {
                let assginRoleVo = {
                    userId: this.sysUser.id,
                    roleIdList: this.userRoleIds
                }
                axios.post("/role/doAssign",assginRoleVo).then((res) => {
                    this.$message.success('分配角色成功')
                    this.dialogRoleVisible = false
                    this.fetchData(this.page)
                })
            },
            //密码显示状态***
            codeMask(val) {
                if (val && val.length > 16) {
                    return val.substr(0, 8) + "*".repeat(val.length - 16) + val.substr(val.length - 8)
                } else {
                    return val
                }
            },
            /*
           全选勾选状态发生改变的监听
           */
            handleCheckAllChange(value) {// value 当前勾选状态true/false
                // 如果当前全选, userRoleIds就是所有角色id的数组, 否则是空数组
                this.userRoleIds = value ? this.allRoles.map(item => item.roleId) : []
                // 如果当前不是全选也不全不选时, 指定为false
                this.isIndeterminate = false
            },

            /*
            角色列表选中项发生改变的监听
            */
            handleCheckedChange(value) {
                const {userRoleIds, allRoles} = this
                this.checkAll = userRoleIds.length === allRoles.length && allRoles.length > 0
                this.isIndeterminate = userRoleIds.length > 0 && userRoleIds.length < allRoles.length
            },
            //展示分配角色
            showAssignRole(row) {
                this.sysUser = row
                this.dialogRoleVisible = true
                axios.get("/role/toAssign?userId=" + row.id).then((res) => {
                    this.userRoleIds=[];
                    this.allRoles = res.data.data.allRoles;
                    for (var i = 0; i < res.data.data.userRoleIds.length; i++) {
                        this.userRoleIds[i] = parseInt(res.data.data.userRoleIds[i]);
                    }
                    console.log(this.userRoleIds)
                    this.checkAll = this.userRoleIds.length === this.allRoles.length; //全选框√
                    this.isIndeterminate = this.userRoleIds.length > 0 && this.userRoleIds.length < this.allRoles.length;
                })
            },
            //切换用户状态
            switchStatus(row) {
                row.status = row.status === 1 ? 0 : 1;
                axios.get("/admin/updateStatus?id=" + row.id + "&status=" + row.status).then((res) => {
                    if (res.data.flag) {
                        this.$message.success('操作成功');
                        this.fetchData(this.page);
                    }
                })
            },
            removeDataById(id) {
                this.$confirm('请问您是否要删除该用户信息?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //执行删除操作
                    axios.post("/admin/del?id=" + id).then((res) => {
                        if (res.data.flag) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }
                        this.fetchData(this.page);
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //更新
            update() {
                axios.post("/admin/update", this.sysUser).then((res) => {
                    this.$message.success('操作成功');
                    this.dialogVisible = false;
                    this.fetchData(this.page);
                })
            },
            //添加
            save() {
                axios.post("/admin/add", this.sysUser).then((res) => {
                    this.$message.success('操作成功');
                    this.dialogVisible = false;
                    this.fetchData(this.page);
                });
            },
            //添加或更新
            saveOrUpdate() {
                if (!this.sysUser.id) {
                    this.save();
                } else {
                    this.update();
                }
            },
            //编辑
            edit(id) {
                this.dialogVisible = true;
                axios({
                    method: "GET",
                    url: "admin/findById",
                    params: {"id": id}
                }).then((res) => {
                    this.sysUser = res.data.data;
                    // 数据加载并绑定成功
                    this.listLoading = false;
                });
            },
            //弹出添加表单
            add() {
                this.dialogVisible = true;
                this.sysUser = {};
            },
            // 加载banner列表数据
            fetchData(page) {
                if (page != null) {
                    this.searchMap.page = 1;
                }
                if (this.createTimes && this.createTimes.length == 2) {
                    this.searchMap.createTimeBegin = this.createTimes[0];
                    this.searchMap.createTimeEnd = this.createTimes[1];
                }
                axios.post("/admin/search", this.searchMap).then((res) => {
                    this.list = res.data.data.records;
                    for (var i = 0; i < this.list.length; i++) {
                        this.list[i].createTime=this.dateFormat(this.list[i].createTime);
                    }
                    this.total = res.data.data.total;
                    // 数据加载并绑定成功
                    this.listLoading = false;
                });
            },
            //日期格式化方法
            //date 要进行格式的日期 ；format 格式化的样式
            dateFormat(date, format) {
                //默认格式化字符串"YYYY-MM-DD HH:mm:ss"
                if (format == null || format == '') {
                    format = "YYYY-MM-DD HH:mm:ss";
                }
                return moment(date).format(format);
            },
            // 重置查询表单
            resetData() {
                console.log('重置查询表单');
                this.searchMap = {
                    "createTimeBegin": "",
                    "createTimeEnd": "",
                    "keyword": this.keyword,
                    "page": 1,
                    "limit": 2
                };
                this.createTimes = [];
                this.fetchData();
            },
            houseFindAllByCommunityName() {
                axios.get("/building/findByCommunityName").then((res) => {
                    this.findByCommunityName = res.data.data;
                });
            },
            buildingFindAllByName(communityName) {
                axios.get("/home/addById?communityName=" + communityName).then((res) => {
                    this.sysUser.communityId = res.data.data + "";
                });
            },
            //handleSizeChange每页数量发生变化后触发的方法
            handleSizeChange(pageSize) {
                this.searchMap.limit = pageSize;
                this.fetchData();
            },
            //handleCurrentChange页码变化触发方法
            handleCurrentChange(pageNum) {
                this.searchMap.page = pageNum;
                this.fetchData();
            },
        },
        created: function () {//Vue生命周期方法，加载页面时会执行该方法
            layui.use(['laydate', 'element', 'laypage', 'layer'], function () {
                $ = layui.jquery;//jquery
                layer = layui.layer;//弹出层
                okLoading.close($);
                layer.ready(function () { //为了layer.ext.js加载完毕再执行
                    layer.photos({
                        photos: '#x-img'
                    });
                });
            });
            this.fetchData();
            this.houseFindAllByCommunityName();
        }
    });

</script>


</body>
</html>
